﻿using System;
using System.CodeDom;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DatabaseManager.Infrastructure.Configuration;
using DatabaseManager.Infrastructure.Connections;
using DatabaseManager.Utilities;
using DatabaseManager.WinForms.Common;
using DatabaseManager.WinForms.Services;
using DevExpress.XtraEditors;
using SqlSugar;

namespace DatabaseManager.WinForms
{
    public partial class MianForm : Form
    {

        //string _dbconnStr = "server=localhost;port=3307;" +
        //    "database=dsm_db;uid=dsm_admin;pwd=dsm123456;charset=utf8mb4";
        //server=localhost;database=dsm_db;uid=dsm_admin;pwd=dsm123456;charset=utf8mb4;port=3307

        //string _dbconnStr = "Server=localhost;Port=3307;" +
        //    "Database=ry-vue;User Id=root;Password=86MpR7dTySLdyAay;charset=utf8mb4; ";
        private readonly ModelGenerationService _modelGenerationService;

        private ISqlSugarClient _dbClient;

        public MianForm()
        {
            InitializeComponent();

            // 初始化依赖链
            IConfigurationProvider configProvider = new AppSettingsConfigurationProvider();
            IDatabaseConnectionFactory connectionFactory = new DatabaseConnectionFactory(configProvider.GetSystemConnectionString());
            var dbConnectionService = new DbConnectionService(configProvider, connectionFactory);

            // 初始化模型生成服务
            _modelGenerationService = new ModelGenerationService(dbConnectionService);


        }

        public void Init()
        {


        }

        public ConnectionConfig GetConnectionConfig(string dbconnStr, DbType dbType)
        {
            ConnectionConfig connectionConfig = new ConnectionConfig()
            {
                ConnectionString = dbconnStr,
                IsAutoCloseConnection = true,
                DbType = dbType,
                InitKeyType = InitKeyType.Attribute
            };
            return connectionConfig;
        }

        public ConnectionConfig GetConnectionConfig(string dbconnStr)
        {
            ConnectionConfig connectionConfig = new ConnectionConfig()
            {
                ConnectionString = dbconnStr,
                IsAutoCloseConnection = true,
                DbType = DbType.MySqlConnector,
                InitKeyType = InitKeyType.Attribute
            };




            return connectionConfig;
        }

        ISqlSugarClient CreateSystemConnection(string dbconnStr)
        {

            ConnectionConfig connectionConfig = new ConnectionConfig();
            connectionConfig.ConnectionString = dbconnStr;
            connectionConfig.DbType = DbType.MySqlConnector;
            connectionConfig.IsAutoCloseConnection = true;
            connectionConfig.InitKeyType = InitKeyType.Attribute;

            SqlSugarClient sqlSugarClient = new SqlSugarClient(connectionConfig);


            //using (SqlSugarClient db = new SqlSugarClient(connectionConfig))
            //{

            //    // 使用DbFirst生成Model类
            //    db.DbFirst
            //        .IsCreateAttribute()  // 创建带有属性注解的实体  
            //        .StringNullable();
            //    //.FormatFileName(t => ToCamelCase(t))
            //    //.FormatClassName(t => ToPascalCase(t))
            //    //.FormatPropertyName(t => ToCamelCase(t))
            //    //.CreateClassFile(modelFileDir, modelNameSpace);

            //    Console.WriteLine("Model类生成完成！");
            //}

            return sqlSugarClient;

            //return new SqlSugarClient(new ConnectionConfig
            //{
            //    ConnectionString = _systemConnectionString,
            //    DbType = DbType.MySql,
            //    IsAutoCloseConnection = true,
            //    InitKeyType = InitKeyType.Attribute
            //});


        }

        private void Test1()
        {
            //try
            //{
            //    if (_dbClient == null)
            //    {
            //        // 创建连接前验证连接字符串
            //        var connectionString = _dbconnStr;
            //        if (string.IsNullOrWhiteSpace(connectionString))
            //        {
            //            throw new InvalidOperationException("数据库连接字符串为空，请检查配置");
            //        }

            //        // 创建连接
            //        _dbClient = CreateSystemConnection(connectionString);

            //        // 验证数据库类型
            //        if (_dbClient.CurrentConnectionConfig.DbType != SqlSugar.DbType.MySqlConnector)
            //        {
            //            var actualDbType = _dbClient.CurrentConnectionConfig.DbType.ToString();
            //            throw new InvalidOperationException($"数据库类型配置错误，应为MySQL，实际为: {actualDbType}");
            //        }
            //    }

            //    // 测试连接
            //    var testResult = _dbClient.Ado.GetScalar("SELECT 1");
            //    //return testResult != null && testResult.ToString() == "1";
            //}
            //catch (Exception ex)
            //{
            //    System.Diagnostics.Trace.WriteLine($"数据库连接失败: {ex.Message}");
            //    //return false;
            //}

        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            //Test1();

            //Test2();

            DbConnectTest();

        }


        /// <summary>
        /// 数据库连接测试
        /// </summary>
        private void DbConnectTest()
        {
            var dbConnectionService = new DbConnectionService();
            dbConnectionService.ConnectTest();
        }

        private void btnGenModels_Click(object sender, EventArgs e)
        {
            // 1. 禁用按钮，防止重复点击
            btnGenModels.Enabled = false;
            progressBar1.Value = 0;
           

            lblProgress.Text = "准备生成...";

            // 2. 配置生成参数（可通过界面输入框让用户指定）
            //string outputDir = @"D:\Projects\YourApp\Models"; // 输出目录
            //string outNamespace = "YourApp.Models"; // 实体类命名空间

            var (outNamespace, outputDir) = ModelGenerationHelper.ProcessNamespaceAndOutputDir(
                this.txtNamespace.Text.Trim(),
                this.txtOutputDir.Text.Trim(),
                @"D:\Temp"); // 可选：指定默认基础目录

            // 3. 初始化进度报告（自动切换到 UI 线程）
            var progress = new Progress<int>(value =>
            {
                // 更新进度条
                progressBar1.Value = value;
                
                // 更新进度文本
                lblProgress.Text = value < 100
                ? $"正在生成... {value}%"
                : "生成完成，正在清理...";
            });

            // 4. 后台执行生成任务（避免 UI 卡顿）
            Task.Run(() =>
            {
                try
                {
                    // 调用生成方法，传入进度回调
                    var result = _modelGenerationService.GenerateModels(outputDir, outNamespace, progress);

                    // 生成完成后在 UI 线程显示结果
                    this.Invoke((Action)(() =>
                    {
                        // 清理 C#8.0 语法（如果需要）
                        if (result.IsSuccess && "FW".Equals(rgYfType.EditValue?.ToString()))
                        {
                            ModelGenerationHelper.CleanNullableSyntax(outputDir);
                        }

                        // 显示结果
                        if (result.IsSuccess)
                        {
                            MessageBox.Show(result.Message, "生成成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            System.Diagnostics.Process.Start("explorer.exe", outputDir);
                        }
                        else
                        {
                            MessageBox.Show(result.Message, "生成失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            string logMessage = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {result.Message}";
                            System.Diagnostics.Trace.WriteLine(logMessage);
                        }

                        // 重置进度控件
                        progressBar1.Value = 0;
                      

                        lblProgress.Text = "就绪";
                        // 恢复按钮可用
                        btnGenModels.Enabled = true;
                    }));
                }
                catch (Exception ex)
                {
                    this.Invoke((Action)(() =>
                    {
                        MessageBox.Show($"执行失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        progressBar1.Value = 0;
                        

                        lblProgress.Text = "就绪";
                        btnGenModels.Enabled = true;
                    }));
                }
            });        
        }

        private void MianForm_Load(object sender, EventArgs e)
        {

            

        }
    }
}